#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2023/4/13 11:07
# @Author  : jiangwei
# @Site    : 
# @File    : util.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from pipeline.cookie_sql import MySqlDB
from jddj.login.login_jddj_playwright import login_for_cookie


def init_jddj_headers(cookie_expire=False, TRY_COUNT=0):
    """
    初始化头信息
    :return:
    """
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        # 'Cookie': 'user=3X6G3XZ3FUU4B74FEZNCUF5UUGVDXCVOHPO4AUV6FVOZPN46T7VZW276UDXLDQCN7MLXBMG5KFKDLEQU7TQA4BVKSR2SANET56YFEPMAA7B3JGKZY7NOYXTVYNO7QQQ75ZDN7JWOKBRC5IPCH3KJ76D3OKM2XIKR2647FJLFT456QLJ7CCZP3ZK5Y7X5IFT3RF44L5F5RHXNM52EMC6CNCFEEI5YWDUKLW43SVGCUJEPP6FAX3QIADCW63IY22AUGO6642AHV5WH5IDZBVRNCDTGOHXBMEY4KPDJTSSIGOCJ43LO3HBE2J3GG6ELRSMNPGDS4ZUOZAEQPFVP7HYD43GIODES62HN2BTVNHGQ2UXGEON35IWXXN2LLH62GHFKGUFTICUEZ4HEKHL6RPE3VDBXNAEMWBIC2BV776C3L72BSSLMLFTQ',
        'Pragma': 'no-cache',
        'Referer': 'https://dfsc.imdada.cn/shibaInu/?timestamp=1681349610955',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    if cookie_expire:
        print("cookie 过期，执行登录重新获取")
        login_for_cookie()

    m = MySqlDB()
    user = "jd_mcyp"
    cookie_in_sql = m.get_cookie(user_name="JDDJ_{}".format(user))
    cookie = cookie_in_sql[0] if cookie_in_sql else ""
    print("sql cookie: ", cookie)

    if cookie:
        headers.update({
            "Cookie": cookie
        })
        m.close()
        return headers

    else:
        TRY_COUNT += 1
        if TRY_COUNT > 2:
            m.close()
            print("重试20次登录依然失败")
            return headers
        return init_jddj_headers(cookie_expire=True, TRY_COUNT=TRY_COUNT)


if __name__ == '__main__':
    init_jddj_headers(cookie_expire=True)
